{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python OS模块介绍\n",
    "**OS:operate systeam**,它是Python标准库中的一个用于访问系统功能的模块<br>\n",
    "1. 导入模块:import os\n",
    "2. OS模块内置方法:\n",
    "    * 系统操作:\n",
    "      * os.sep#用于系统路径的分隔符\n",
    "      * os.getcwd() # 获取当前工作目录，非脚本目录\n",
    "    * 目录操作(增删改查):\n",
    "       * 增 \n",
    "          * os.mkdir(\"test\") # 创建单个目录\n",
    "          * os.makedirs(r\"c:\\python\\test\") # 创建多级目录\n",
    "       * 删\n",
    "          * os.remove() # 删除文件\n",
    "          * os.removedirs() #删除目录\n",
    "          * os.rmdir()删除空目录。目录中有文件则无法删除\n",
    "       * 查\n",
    "          * os.listdir()  返回指定目录下的所有文件和目录，非递归\n",
    "          * os.path.split()  返回一个路径的目录名和文件名\n",
    "          * os.path.getsize(filename) # 获取文件大小\n",
    "          * os.path.dirname()  获取文件路径名\n",
    "          * os.path.basename()  获取一个绝对路径下的文件名\n",
    "       * 改\n",
    "          * os.rename(old,new) # 重命名文件或目录\n",
    "          * os.path.splitext() # 分离文件扩展名\n",
    "    * 判断    \n",
    "        * os.path.isfile() # 检验给出的路径是否是一个文件\n",
    "        * os.path.isdir() # 检验给出的路径是否是一个目录\n",
    "        * os.path.isabs() # 判断是否是绝对路径\n",
    "        * os.path.exists() # 检验给出的路径是否真实存在\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入模块\n",
    "import os"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 系统操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\\\'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "os.sep#用于系统路径的分隔符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'C:\\\\Users\\\\1\\\\代码\\\\2020励能计划-讲义\\\\第四周'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "os.getcwd() # 获取当前工作目录，非脚本目录"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 实用案例之批量修改文件后缀名"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 将xlsx文件转为xls"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# 列出当前目录下所有的文件\n",
    "files = os.listdir('.')  # 如果path为None，则使用path = '.' \n",
    "\n",
    "for filename in files:\n",
    "    portion = os.path.splitext(filename)  # 分离文件名与扩展名\n",
    "    # 如果后缀是xlsx\n",
    "    if portion[1] == '.xlsx':\n",
    "        # 重新组合文件名和后缀名\n",
    "        newname = portion[0] + '.xls'\n",
    "        os.rename(filename, newname)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 将jpg图片转为png"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "# 列出当前目录下所有的文件\n",
    "photos = os.listdir('.')  # 如果path为None，则使用path = '.' \n",
    "\n",
    "for filename in photos:\n",
    "    portion = os.path.splitext(filename)  # 分离文件名与扩展名\n",
    "    # 如果后缀是.jpg\n",
    "    if portion[1] == '.jpg':   #==表示等于的意思\n",
    "        # 重新组合文件名和后缀名\n",
    "        newname = portion[0] + '.png'    #变量与字符串的拼接要用+号\n",
    "        os.rename(filename, newname)  #os.rename()重命名"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# with 语句管理上下文\n",
    "with语句会管理代码组运行的上下文，结合使用with和open时，解释器会为你完成收尾的清理工作，在需要时调用close"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python文件模式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "模式|描述\n",
    ":---|:---\n",
    "r|只读模式\n",
    "w|只写模式，创建新文件(文件存在时会覆盖原有数据)\n",
    "x|只写模式，创建新文件，但存在同名路径时会创建失败\n",
    "a|添加到已经存在的文件(如果不存在就创建)\n",
    "r+|读写模式\n",
    "b|二进制文件模式，添加到别的模式中(比如“rb”或‘rb’)\n",
    "t|文件的文本模式(自动将字节解码为Unicode)。如果没有指明模式，默认使用此模式。可以添加到别的模式中(例如‘rt’,'xt')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 重要的Python文件方法及属性"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "方法|描述\n",
    ":---|:---\n",
    "read(size)|将文件数据作为字符串返回，可选参数size控制读取的字节数\n",
    "readlines([size])|返回文件中行内容的列表，size参数可选\n",
    "write(str)|将字符串写入文件\n",
    "writelines(strings)|将字符串序列写入文件\n",
    "close()|关闭文件"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 不使用with语句打开文件\n",
    "很容易忘记xxx.close()关闭文件；若是在文件中写入数据的话,那就很容易造成数据的丢失或者破坏。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "#打开文件，将文件流赋给一个变量tasks；\n",
    "#open用于打开/新建文件，第一个参数是文件名(若文件不存在，则自动生成一个新文件)，第二个参数是Python文件模式\n",
    "tasks=open('text.txt','w')\n",
    "#.write是Python文件方法：将字符串写入文件\n",
    "tasks.write(\"Hello World\")\n",
    "tasks.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用with语句打开文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "code_folding": []
   },
   "outputs": [],
   "source": [
    "#下边这2行等于上边这3行\n",
    "with open(\"text.txt\",'w') as tasks:\n",
    "    tasks.write(\"Hello World\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
